using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for CommonFunctions
/// </summary>
public class CommonFunctions
{
    private struct serverSettings
    {
        public string name;
        public int port;
        public string username;
        public string password;
    }
	public CommonFunctions()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    
    #region Old implementation
    public string sendMail(string toAddress, string fromAddress, bool isHTML, string content, string subject)
    {
        //return sendEmail(toAddress, fromAddress, isHTML, subject, content, null, "", "mail.cellarstone.com", 25, "sync@cellarstone.com", "sync123");
        return sendEmail(toAddress, fromAddress, isHTML, subject, content, null, "");
        //return sendEmail("MaxBlox_Support@cellarstone.com", email, true, subject, comments, screenshot, attachFileName, "mail.cellarstone.com", 25, "sync@cellarstone.com", "sync123") == "success";
    }
    private serverSettings getEmailServerCredentials()
    {
        serverSettings ret = new serverSettings();
        ret.name = "";
        try
        {
            if (HttpContext.Current.Session["servercon"] != null)
            {
                HDDatabase hdd = null;
                try
                {
                    hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
                    DataTable dt = hdd.GetDataTable("select * from email_server_settings where active=1 order by sequence");
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            DataRow dr = dt.Rows[0];
                            ret.name = dr["name"].ToString();
                            ret.port = dr["port"].ToString() == "" ? 0 : Convert.ToInt32(dr["port"].ToString());
                            ret.username = dr["username"].ToString();
                            ret.password = dr["password"].ToString();
                        }
                    }

                }
                catch (Exception ee)
                {
                    LogWriter.WriteLog("Error in getEmailServerCredentials function. " + ee.Message);
                }
                finally
                {
                    hdd = null;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in getEmailServerCredentials function." + e.Message);
        }
        return ret;
    }

    //public string sendEmail(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName, string server, int serverPort, string serverUserName, string serverPassword)
    public string sendEmail(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName)
    {
        try
        {
            System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
            //eMail = new MailMessage();
            if (attachFile != null)
            {
                //System.Net.Mail.Attachment att;
                //att = getAttachment(attachFiles[i]);
                //if (att != null)
                //    eMail.Attachments.Add(att);
                MemoryStream ms = new MemoryStream(attachFile);
                eMail.Attachments.Add(new System.Net.Mail.Attachment(ms, attachmentFileName, "image/png"));
            }
            eMail.IsBodyHtml = isHTML;
            //eMail.BodyFormat = System.Net.Mail.MailFormat.Html;
            eMail.Body = content;
            //eMail.From = new System.Net.Mail.MailAddress(fromAddress);
            eMail.Subject = subject;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtsperver"] = server;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
            ////////                if (SMTPUser != null && SMTPPassword != null)
            ////////                {
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "mail@visioninfomedia.com";
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "indi";
            //                }
            //eMail.To.Add(toAddress);

            AddAddressToMail(ref eMail, "to", toAddress);
            AddAddressToMail(ref eMail, "from", fromAddress);

            //System.Net.Mail.SmtpMail.SmtpServer = server;// Smtpmail;// = new System.Net.Mail.SmtpMail();
            //System.Net.Mail.SmtpMail.Send(eMail);
            serverSettings ss = getEmailServerCredentials();
            if (ss.name.Length > 0)
            {
                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(ss.name);
                sc.Timeout = 400000;
                if (ss.port != 0) sc.Port = ss.port;
                if (ss.username.Trim() != "")
                    sc.Credentials = new NetworkCredential(ss.username, ss.password);
                else
                    sc.Credentials = CredentialCache.DefaultNetworkCredentials;
                //sc.Credentials  = CredentialCache.

                //                Smtpmail.SmtpServer = "localhost";
                //                Smtpmail.Send(eMail);
                sc.Send(eMail);
                eMail = null;
                sc = null;
                return "success";
            }
            else
                return "No server settings found.";
        }
        catch (Exception e)
        {
            //return false;
            return e.Message;
        }
    }

    public string sendEmail(string toAddress, string fromAddress, string fromAddressDisplayName, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName)
    {
        try
        {
            System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
            //eMail = new MailMessage();
            if (attachFile != null)
            {
                //System.Net.Mail.Attachment att;
                //att = getAttachment(attachFiles[i]);
                //if (att != null)
                //    eMail.Attachments.Add(att);
                MemoryStream ms = new MemoryStream(attachFile);
                eMail.Attachments.Add(new System.Net.Mail.Attachment(ms, attachmentFileName, "image/png"));
            }
            eMail.IsBodyHtml = isHTML;
            //eMail.BodyFormat = System.Net.Mail.MailFormat.Html;
            eMail.Body = content;
            if (fromAddressDisplayName != "")
            {
                eMail.From = new System.Net.Mail.MailAddress(fromAddress, fromAddressDisplayName);
            }
            else
            {
                eMail.From = new System.Net.Mail.MailAddress(fromAddress);
            }
            eMail.Subject = subject;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtsperver"] = server;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
            ////////                if (SMTPUser != null && SMTPPassword != null)
            ////////                {
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "mail@visioninfomedia.com";
            //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "indi";
            //                }
            //eMail.To.Add(toAddress);

            AddAddressToMail(ref eMail, "to", toAddress);
            //System.Net.Mail.SmtpMail.SmtpServer = server;// Smtpmail;// = new System.Net.Mail.SmtpMail();
            //System.Net.Mail.SmtpMail.Send(eMail);
            serverSettings ss = getEmailServerCredentials();
            if (ss.name.Length > 0)
            {
                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(ss.name);
                sc.Timeout = 400000;
                if (ss.port != 0)
                    sc.Port = ss.port;
                if (ss.username.Trim() != "")
                    sc.Credentials = new NetworkCredential(ss.username, ss.password);
                else
                    sc.Credentials = CredentialCache.DefaultNetworkCredentials;
                //sc.Credentials  = CredentialCache.

                //                Smtpmail.SmtpServer = "localhost";
                //                Smtpmail.Send(eMail);
                sc.Send(eMail);
                eMail = null;
                sc = null;
                return "success";
            }
            else
                return "No server settings found.";
        }
        catch (Exception e)
        {
            //return false;
            return e.Message;
        }
    }
    #endregion

    private serverSettings getEmailServerCredentials(bool CompanyServerSettings) //Added by srivatsan
    {
        serverSettings ret = new serverSettings();
        ret.name = "";
        try
        {
                    HDDatabase hdd = null;
                    string sql = "";
                    try
                    {
                        if (CompanyServerSettings)
                        {
                            if (HttpContext.Current.Session["dbcon"] != null)
                                hdd = new HDDatabase(HttpContext.Current.Session["dbcon"].ToString());

                            sql = "select top 1 * from sy_email_server_settings where active=1 order by sequence";
                        }
                        else
                        {
                            if (HttpContext.Current.Session["servercon"] != null)
                                hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
                            sql = "select top 1 * from email_server_settings where active=1 order by sequence";
                        }
                            if(hdd !=null)
                            {
                                DataTable dt = hdd.GetDataTable(sql);
                                if (dt != null)
                                    if (dt.Rows.Count > 0)
                                    {
                                        DataRow dr = dt.Rows[0];
                                        ret.name = dr["name"].ToString();
                                        ret.port = dr["port"].ToString() == "" ? 0 : Convert.ToInt32(dr["port"].ToString());
                                        ret.username = dr["username"].ToString();

                                        if (CompanyServerSettings)
                                                ret.password = dr["password"].ToString().Trim() != "" ? security.decrypt(dr["password"].ToString()) : dr["password"].ToString();
                                        else
                                            ret.password = dr["password"].ToString();
                                    }
                            }
                    }
                    catch (Exception ee)
                    {
                        LogWriter.WriteLog("Error in getEmailServerCredentials function. " + ee.Message);
                    }
                    finally
                    {
                        hdd = null;
                    }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in getEmailServerCredentials function." + e.Message);
        }
        return ret;
    }


    public string sendMail(string toAddress, string fromAddress, bool isHTML, string content, string subject, string ccAddress, string bccAddress, bool CompanyServerSettings)
    {
        return sendEmail(toAddress, fromAddress, isHTML, subject, content, null, "", ccAddress, bccAddress, CompanyServerSettings);
    }

    public string sendEmail(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName, string ccAddress, string bccAddress, bool CompanyServerSettings)
    {
        try
        {
            System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
            if (attachFile != null)
            {
                MemoryStream ms = new MemoryStream(attachFile);
                eMail.Attachments.Add(new System.Net.Mail.Attachment(ms, attachmentFileName, "image/png"));
            }
            eMail.IsBodyHtml = isHTML;
            eMail.Body = content;
            eMail.Subject = subject;
            AddAddressToMail(ref eMail, "from", fromAddress);
            AddAddressToMail(ref eMail, "to", toAddress);
            AddAddressToMail(ref eMail, "cc", ccAddress);
            AddAddressToMail(ref eMail, "bcc", bccAddress);

            serverSettings ss = getEmailServerCredentials(CompanyServerSettings);
            if (ss.name.Length > 0)
            {
                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(ss.name);
                sc.Timeout = 400000;
                if (ss.port != 0) sc.Port = ss.port;
                if (ss.username.Trim() != "")
                    sc.Credentials = new NetworkCredential(ss.username, ss.password);
                else
                    sc.Credentials = CredentialCache.DefaultNetworkCredentials;

                sc.Send(eMail);
                eMail = null;
                sc = null;
                return "success";
            }
            else
                return "No server settings found.";
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }

    public string sendEmail(string toAddress, string fromAddress, string fromAddressDisplayName, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName, string ccAddress, string bccAddress, bool CompanyServerSettings)
    {
        try
        {
            System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
            if (attachFile != null)
            {
                MemoryStream ms = new MemoryStream(attachFile);
                eMail.Attachments.Add(new System.Net.Mail.Attachment(ms, attachmentFileName, "image/png"));
            }
            eMail.IsBodyHtml = isHTML;
            eMail.Body = content;
            if (fromAddressDisplayName != "")
            {
                eMail.From = new System.Net.Mail.MailAddress(fromAddress, fromAddressDisplayName);
            }
            else
            {
                eMail.From = new System.Net.Mail.MailAddress(fromAddress);
            }
            eMail.Subject = subject;
            AddAddressToMail(ref eMail,"to",toAddress);
            AddAddressToMail(ref eMail, "cc", ccAddress);
            AddAddressToMail(ref eMail, "bcc", bccAddress);

            serverSettings ss = getEmailServerCredentials(CompanyServerSettings);
            if (ss.name.Length > 0)
            {
                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(ss.name);
                sc.Timeout = 400000;
                if (ss.port != 0)
                    sc.Port = ss.port;
                if (ss.username.Trim() != "")
                    sc.Credentials = new NetworkCredential(ss.username, ss.password);
                else
                    sc.Credentials = CredentialCache.DefaultNetworkCredentials;
                
                sc.Send(eMail);
                eMail = null;
                sc = null;
                return "success";
            }
            else
                return "No server settings found.";
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
    private void AddAddressToMail(ref System.Net.Mail.MailMessage eMail,string type, string address)
    {
        try
        {
            if (address.Trim() != "")
            {
                string[,] arrfrom = GetEmailAndNameInArray(address);
                if (arrfrom != null)
                {
                    int cnt = arrfrom.GetLength(0);
                    for (int i = 0; i < cnt; i++)
                    {
                        if (arrfrom[i,1].ToString().Trim() != "")
                        {
                            switch (type.ToLower())
                            {
                                case "from":
                                    if (arrfrom[i,0].ToString().Trim() != "")
                                        eMail.From = new System.Net.Mail.MailAddress(arrfrom[i,1].ToString(), arrfrom[i,0].ToString());
                                    else
                                        eMail.From = new System.Net.Mail.MailAddress(arrfrom[i,1].ToString());
                                    break;
                                case "to":
                                    if (arrfrom[i,0].ToString().Trim() != "")
                                        eMail.To.Add(new System.Net.Mail.MailAddress(arrfrom[i,1].ToString(), arrfrom[i,0].ToString()));
                                    else
                                        eMail.To.Add(new System.Net.Mail.MailAddress(arrfrom[i,1].ToString()));
                                    break;
                                case "cc":
                                    if (arrfrom[i,0].ToString().Trim() != "")
                                        eMail.CC.Add(new System.Net.Mail.MailAddress(arrfrom[i,1].ToString(), arrfrom[i,0].ToString()));
                                    else
                                        eMail.CC.Add(new System.Net.Mail.MailAddress(arrfrom[i,1].ToString()));
                                    break;
                                case "bcc":
                                    if (arrfrom[i,0].ToString().Trim() != "")
                                        eMail.Bcc.Add(new System.Net.Mail.MailAddress(arrfrom[i,1].ToString(), arrfrom[i,0].ToString()));
                                    else
                                        eMail.Bcc.Add(new System.Net.Mail.MailAddress(arrfrom[i,1].ToString()));
                                    break;
                            }

                        }
                    }
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : AddAddressToMail :"+ ex.Message);
        }
    }



    /// <summary>
    /// This function will return True if Email server setting in Company database can be used.
    /// </summary>
    /// <returns></returns>
    private bool UseCompanyEmailServerSettings()//srivatsan Feb 19 2010
    {
        bool status = false;
        HDDatabase hdd = null;
        try
        {
            hdd = new HDDatabase();
            string sql = "select mem_value1 from sy_acr_mem where af_row_id = '1d2e972deaa0b88e'";
            string result = hdd.GetColumnValue(sql);
            status = result.ToString() != "" ? Convert.ToBoolean(result) : false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : UseCompanyEmailServerSettings : " + ex.Message);
        }
        finally
        {
            hdd = null;
        }
        return status;
    }

    /// <summary>
    /// This function will return true if MaxBlox Email Compose page can be used
    /// </summary>
    /// <returns></returns>
    private bool UseMaxBloxEmailCompose()//srivatsan
    {
        bool status = false;
        HDDatabase hdd = null;
        try
        {
            hdd = new HDDatabase();
            string sql = "select mem_value1 from sy_acr_mem where af_row_id = '62b95ed0102fc1cb'";
            string result = hdd.GetColumnValue(sql);
            status = result.Trim() != "" ? Convert.ToBoolean(result) : false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : UseMaxBloxEmailCompose :" + ex.Message);
        }
        finally
        {
            hdd = null;
        }
        return status;
    }

    /// <summary>
    /// This function will get the Email and DisplayName seperated in string array
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private string[,] GetEmailAndNameInArray(string input)
    {
        string[,] result = null;
        try
        {
            if (input.Trim() != "")
            {
                if (input.Contains(";"))
                {
                    string[] ArrMail = input.Split(';');
                    if (ArrMail.Length > 0)
                    {
                        int rdim = ArrMail.Length;
                        result = new string[rdim, 2];
                        for (int i = 0; i < rdim; i++)
                        {
                            string[] arr = SplitEmailAndName(ArrMail[i].ToString());
                            if (arr != null)
                            {
                                result[i, 0] = arr[0].ToString();
                                result[i, 1] = arr[1].ToString();
                            }
                        }
                    }
                }
                else if (input.Contains(","))
                {
                    string[] ArrMail = input.Split(',');
                    if (ArrMail.Length > 0)
                    {
                        int rdim = ArrMail.Length;
                        result = new string[rdim, 2];
                        for (int i = 0; i < rdim; i++)
                        {
                            string[] arr = SplitEmailAndName(ArrMail[i].ToString());
                            if (arr != null)
                            {
                                result[i, 0] = arr[0].ToString();
                                result[i, 1] = arr[1].ToString();
                            }
                        }
                    }
                }
                else
                {
                    result = new string[1, 2];
                    string[] splitarr = SplitEmailAndName(input);
                    if (splitarr != null)
                    {
                        result[0, 0] = splitarr[0].ToString();
                        result[0, 1] = splitarr[1].ToString();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetEmailAndNameInArray :" + ex.Message);
        }

        return result;
    }

    /// <summary>
    /// This function will split Email and Display Name
    /// </summary>
    /// <param name="inp"></param>
    /// <returns></returns>
    private string[] SplitEmailAndName(string inp)
    {
        string[] result = null;
        try
        {
            if (inp.Trim() != "")
            {
                result = new string[2];
                if (inp.Contains("<"))
                {
                    string[] arr = inp.Split('<');
                    if (arr.Length > 0)
                    {
                        result[0] = arr[0]; //Displayname
                        result[1] = arr[1].Substring(0, arr[1].IndexOf(">")); //Email id
                    }
                }
                else if(inp.Contains("["))
                {
                    string[] arr = inp.Split('[');
                    if (arr.Length > 0)
                    {
                        result[0] = arr[0]; //Displayname
                        result[1] = arr[1].Substring(0, arr[1].IndexOf("]")); //Email id
                    }
                }

                else
                {
                    result[0] = "";
                    result[1] = inp;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SplitEmailAndName : " + ex.Message);
        }
        return result;
    }

    /// <summary>
    /// This function will send Email based on the sy_acr configurations
    /// </summary>
    /// <param name="toAddress"></param>
    /// <param name="fromAddress"></param>
    /// <param name="isHTML"></param>
    /// <param name="subject"></param>
    /// <param name="content"></param>
    /// <param name="attachFile"></param>
    /// <param name="attachmentFileName"></param>
    /// <param name="ccAddress"></param>
    /// <param name="bccAddress"></param>
    /// <returns></returns>
    public string SendEmailBasedOnConfig(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName, string ccAddress, string bccAddress)
    {
            bool UseCompanyServerSettings = UseCompanyEmailServerSettings();
           return sendEmail(toAddress, fromAddress, isHTML, subject, content, attachFile, attachmentFileName, ccAddress, bccAddress, UseCompanyServerSettings);
    }

    /// <summary>
    ///  This will Send Email based on the settings in Company Server Settings
    /// </summary>
    /// <param name="toAddress"></param>
    /// <param name="fromAddress"></param>
    /// <param name="isHTML"></param>
    /// <param name="subject"></param>
    /// <param name="content"></param>
    /// <param name="attachFile"></param>
    /// <param name="attachmentFileName"></param>
    /// <param name="ccAddress"></param>
    /// <param name="bccAddress"></param>
    /// <returns></returns>
    public string SendEmailBasedOnCompanyServerSettings(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName, string ccAddress, string bccAddress)
    {
           return sendEmail(toAddress, fromAddress, isHTML, subject, content, attachFile, attachmentFileName, ccAddress, bccAddress, true);
    }

    /// <summary>
    /// This function accepts Email Address parameters as Objects. Supported objects string,string[],mailaddress,mailaddress[],hashtable
    /// </summary>
    /// <param name="toaddress"></param>
    /// <param name="fromaddress"></param>
    /// <param name="isHTML"></param>
    /// <param name="subject"></param>
    /// <param name="content"></param>
    /// <param name="attachFile"></param>
    /// <param name="attachmentFileName"></param>
    /// <param name="ccAddress"></param>
    /// <param name="bccAddress"></param>
    /// <param name="UseCompanyServerSettings"></param>
    /// <returns></returns>
    public string sendMail(object toaddress, object fromaddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName,object ccAddress,object bccAddress,bool UseCompanyServerSettings)
    {
        string result = "";
        try
        {
            string strToAddress = GetAddressFromObject(toaddress);
            string strFromAddress = GetAddressFromObject(fromaddress);
            string strCCAddress = GetAddressFromObject(ccAddress);
            string strBCCAddress = GetAddressFromObject(bccAddress);
            result = sendEmail(strToAddress, strFromAddress, isHTML, subject, content, attachFile, attachmentFileName, strCCAddress, strBCCAddress, UseCompanyServerSettings);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : sendMail : "+ ex.Message);
        }
        return result;
    }

    /// <summary>
    /// This function will get email ids in different object types and return Email addresses as string.
    /// Objects supported string,string[],mailaddress,mailaddress[],hashtable
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    private string GetAddressFromObject(object obj)
    {
       string result = "";
        try
        {
            switch (obj.GetType().Name.ToLower())
            {
                case "string":
                    string str = (string)obj;
                    result = str;
                    break;
                case "string[]":
                    string[] strarr = (string[])obj;
                    string strresult = "";
                    for (int i = 0; i < strarr.Length; i++)
                    {
                        strresult = strresult + strarr[i] + ";";
                    }
                    result = strresult;
                        break;
                case "arraylist":
                    //ArrayList list = (ArrayList)obj;
                    break;
                case "mailaddress":
                    System.Net.Mail.MailAddress madd = (System.Net.Mail.MailAddress)obj;
                    result = madd.DisplayName + "<" + madd.Address + ">";
                    madd = null;
                    break;
                case "mailaddress[]":
                    System.Net.Mail.MailAddress[] arradd = (System.Net.Mail.MailAddress[])obj;
                    string straddress = "";
                    foreach(System.Net.Mail.MailAddress address in arradd)
                    {
                        if (address != null)
                            if (address.DisplayName.Trim() != "")
                                straddress = straddress + " " + address.DisplayName + "<" + address.Address + ">;";
                            else
                                straddress = address.Address + ";";
                    }
                    arradd = null;
                    result = straddress;
                    break;
                case "hashtable":
                    Hashtable hsh = (Hashtable)obj;
                    if (hsh.Count > 0)
                        foreach (string key in hsh.Keys)
                        {
                            result = result + " " + key + "<" + hsh[key].ToString() + ">;";
                        }
                    hsh = null;
                    break;
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetAddressFromObject :"+ ex.Message);
        }
            return result;
        }


    #region functions added by Sampath for Encoding/Decoding on 10-Nov-2011
    public static void encodeData(DataSet ds)
    {
        try
        {
            foreach (DataTable dt in ds.Tables)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        try
                        {
                            if (checkSystemField(dc.ColumnName)) continue;
                            if (dr[dc] == System.DBNull.Value) continue;
                            if (dr[dc].ToString() == "") continue;
                            dr[dc] = HttpContext.Current.Server.HtmlEncode(dr[dc].ToString());
                        }
                        catch (Exception innerEx)
                        {
                            LogWriter.WriteLog("Error : encodeDataset-1 :" + innerEx.Message);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : encodeDataset :" + ex.Message);
        }
    }

    public static void encodeData(DataTable dt)
    {
        try
        {
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    try
                    {
                        if (checkSystemField(dc.ColumnName)) continue;
                        if (dr[dc] == System.DBNull.Value) continue;
                        if (dr[dc].ToString() == "") continue;
                        dr[dc] = HttpContext.Current.Server.HtmlEncode(dr[dc].ToString());
                    }
                    catch (Exception innerEx)
                    {
                        LogWriter.WriteLog("Error : encodeDataTable-1 :" + innerEx.Message);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : encodeDataTable :" + ex.Message);
        }
    }

    public static void decodeData(DataSet ds)
    {
        try
        {
            foreach (DataTable dt in ds.Tables)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        try
                        {
                            if (checkSystemField(dc.ColumnName)) continue;
                            if (dr[dc] == System.DBNull.Value) continue;
                            if (dr[dc].ToString() == "") continue;
                            dr[dc] = HttpContext.Current.Server.HtmlDecode(dr[dc].ToString());
                        }
                        catch (Exception innerEx)
                        {
                            LogWriter.WriteLog("Error : decodeDataset-1 :" + innerEx.Message);
                        }
                    }
                }
            }
            ds.AcceptChanges();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : decodeDataset :" + ex.Message);
        }
    }

    private static bool checkSystemField(string colname)
    {
        bool isTrue = false;
        try
        {
            switch (colname.ToLower())
            { 
                case "af_row_id":
                case "created_at":
                case "created_by":
                case "modified_by":
                case "modified_at":
                case "owner_id":
                    isTrue = true;
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : checkSystemField :" + ex.Message);
        }
        return isTrue;
    }

    public static void decodeData(DataTable dt)
    {
        try
        {
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    try
                    {
                        if (checkSystemField(dc.ColumnName)) continue;
                        if (dr[dc] == System.DBNull.Value) continue;
                        if (dr[dc].ToString() == "") continue;
                        dr[dc] = HttpContext.Current.Server.HtmlDecode(dr[dc].ToString());
                    }
                    catch (Exception innerEx)
                    {
                        LogWriter.WriteLog("Error : decodeDataTable-1 :" + innerEx.Message);
                    }
                }
            }
            dt.AcceptChanges();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : decodeDataTable :" + ex.Message);
        }
    }

    public static void decodeData(DataRow dr)
    {
        try
        {
            foreach (DataColumn dc in dr.Table.Columns)
            {
                try
                {
                    if (checkSystemField(dc.ColumnName)) continue;
                    if (dr[dc] == System.DBNull.Value) continue;
                    if (dr[dc].ToString() == "") continue;
                    dr[dc] = HttpContext.Current.Server.HtmlDecode(dr[dc].ToString());
                }
                catch (Exception innerEx)
                {
                    LogWriter.WriteLog("Error : decodeDataRow-1 :" + innerEx.Message);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : decodeDataRow :" + ex.Message);
        }
    }
    #endregion

    #region System variable Code
    /// <summary>
    /// To replace system variables from the string.
    /// </summary>
    /// <param name="strValue">String which contains system variables.</param>
    /// <returns>Proper string with system variable values.</returns>
    public static string replaceSystemVariables(string strValue) // Implemented by 'Imran Gani' on 27-Dec-12
    {
        HDDatabase hdd = new HDDatabase();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        Hashtable sysVar = new Hashtable();
        Hashtable sysVarforDQ = new Hashtable();
        string strSQL = "";//, sKeys="";
        //string[] strKeys;
        try
        {
            dt = hdd.GetDataTable("select * from sy_var");
            foreach (DataRow dr in dt.Rows)
            {
                switch (dr["sy_var_type"].ToString())
                {
                    case "DQ"://database query
                        sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_defaultvalue"]);
                        strSQL = ReplaceAppVariables(dr["sy_var_value"].ToString());
                        if (strSQL != "")
                            sysVarforDQ.Add("{!" + dr["sy_var_name"].ToString() + "}", strSQL + ";");
                        break;
                    case "CO"://constant
                        if (dr["sy_var_value"].ToString().Length > 0)
                            sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_value"]);
                        else
                            sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_defaultvalue"]);
                        break;
                }
            }
            //strSQL = "";
            //foreach (string sKey in sysVarforDQ.Keys)
            //{
            //    strSQL += sysVarforDQ[sKey].ToString();
            //    sKeys += sKey + "|";
            //}
            //if (strSQL != "")
            //{
            //    ds = hdd.GetDataset(strSQL);
            //    if (ds.Tables.Count > 0)
            //    {
            //        strKeys = sKeys.Split('|');
            //        for (int i = 0; i < strKeys.Length - 1; i++)
            //        {
            //            if (ds.Tables[i] != null && ds.Tables[i].Rows.Count > 0)
            //            {
            //                sysVar[strKeys[i].ToString()] = ds.Tables[i].Rows[0][0].ToString();
            //            }
            //        }
            //    }
            //}

            // Added by 'Imran Gani' on 07-Jan-2013, to get values one by one,
            // where dataset not working for invalid query inbetween.
            foreach (string sKey in sysVarforDQ.Keys)
            {
                if (sysVarforDQ[sKey].ToString() != "")
                {
                    dt = hdd.GetDataTable(sysVarforDQ[sKey].ToString());
                    if (dt != null && dt.Rows.Count > 0)
                        sysVar[sKey] = dt.Rows[0][0].ToString();
                }
            }
            foreach (string s in sysVar.Keys)
            {
                if (strValue.Contains(s))
                {
                    strValue = strValue.Replace(s, SafeEncode(sysVar[s].ToString()));
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : replaceSystemVariables :" + ex.Message);
        }
        finally
        {
            dt.Dispose();
            ds.Dispose();
            hdd = null;
            sysVar.Clear();
        }
        return strValue;
    }

    /// <summary>
    /// Will replace the application variable in the string.
    /// </summary>
    /// <param name="value">String which contains application variables.</param>
    /// <returns>Proper string with application variable values.</returns>
    public static string ReplaceAppVariables(string value) // Implemented by 'Imran Gani' on 27-Dec-12
    {
        security hdds = new security();
        Hashtable hsAppVar = new Hashtable();
        try
        {
            hdds.loadAppVariables(ref hsAppVar);
            if (hsAppVar != null)
            {
                foreach (string sKey in hsAppVar.Keys)
                {
                    if (value.Contains(sKey))
                        value = value.Replace(sKey, hsAppVar[sKey].ToString());
                }
            }
            return value;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in ReplaceAppVariables function: " + e.Message);
            return "";
        }
    }
    #endregion

    #region Safe Encode
    /// <summary>
    /// To replace the melicious string with encoded string.
    /// </summary>
    /// <param name="strValue">Input string which has melicious text.</param>
    /// <returns>Proper encoded string.</returns>
    // Implemented by 'Imran Gani' on 10-Jan-2013, for safe encoding of XSS(Cross-site Scripting).
    public static string SafeEncode(string strValue)
    {
        string[] strXSS = { "<SCRIPT>", "</SCRIPT>", "<OBJECT>", "</OBJECT>", "<APPLET>", "</APPLET>", "<EMBED>", "</EMBED>", "<FORM>", "</FORM>" };
        try
        {
            foreach (string sKey in strXSS)
            {
                if (strValue.ToUpper().Contains(sKey))
                {
                    //string sTemp = strValue.Substring(strValue.ToUpper().IndexOf(sKey), sKey.Length); // Commanded by 'Imran Gani' on 10-Jan-2013.
                    strValue = Regex.Replace(strValue, sKey, HttpUtility.HtmlEncode(sKey), RegexOptions.IgnoreCase);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SafeEncode :" + ex.Message);
        }
        finally
        {}
        return strValue;
    }
    #endregion

    #region OLD Code
    //public string sendMail(string toAddress, string fromAddress, bool isHTML, string content,string subject)
    //{
    //    //return sendEmail(toAddress, fromAddress, isHTML, subject, content, null, "", "mail.cellarstone.com", 25, "sync@cellarstone.com", "sync123");
    //    return sendEmail(toAddress, fromAddress, isHTML, subject, content, null, "");
    //    //return sendEmail("MaxBlox_Support@cellarstone.com", email, true, subject, comments, screenshot, attachFileName, "mail.cellarstone.com", 25, "sync@cellarstone.com", "sync123") == "success";
    //}
    //private serverSettings getEmailServerCredentials()
    //{
    //    serverSettings ret = new serverSettings();
    //    ret.name = "";
    //    try
    //    {
    //        if (HttpContext.Current.Session["servercon"] != null)
    //        {
    //            HDDatabase hdd = null;
    //            try
    //            {
    //                hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
    //                DataTable dt = hdd.GetDataTable("select * from email_server_settings where active=1 order by sequence");
    //                if (dt != null)
    //                {
    //                    if (dt.Rows.Count > 0)
    //                    {
    //                        DataRow dr = dt.Rows[0];
    //                        ret.name = dr["name"].ToString();
    //                        ret.port = dr["port"].ToString()=="" ? 0 : Convert.ToInt32(dr["port"].ToString());
    //                        ret.username = dr["username"].ToString();
    //                        ret.password = dr["password"].ToString();
    //                    }
    //                }

    //            }
    //            catch (Exception ee)
    //            {
    //                LogWriter.WriteLog("Error in getEmailServerCredentials function. " + ee.Message);
    //            }
    //            finally
    //            {
    //                hdd = null;
    //            }
    //        }
    //    }
    //    catch (Exception e)
    //    {
    //        LogWriter.WriteLog("Error in getEmailServerCredentials function." + e.Message);
    //    }
    //    return ret;
    //}

    ////public string sendEmail(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName, string server, int serverPort, string serverUserName, string serverPassword)
    //public string sendEmail(string toAddress, string fromAddress, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName)
    //{
    //    try
    //    {
    //        System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
    //        //eMail = new MailMessage();
    //        if (attachFile != null)
    //        {
    //            //System.Net.Mail.Attachment att;
    //            //att = getAttachment(attachFiles[i]);
    //            //if (att != null)
    //            //    eMail.Attachments.Add(att);
    //            MemoryStream ms = new MemoryStream(attachFile);
    //            eMail.Attachments.Add(new System.Net.Mail.Attachment(ms, attachmentFileName, "image/png"));
    //        }
    //        eMail.IsBodyHtml = isHTML;
    //        //eMail.BodyFormat = System.Net.Mail.MailFormat.Html;
    //        eMail.Body = content;
    //        eMail.From = new System.Net.Mail.MailAddress(fromAddress);
    //        eMail.Subject = subject;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtsperver"] = server;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
    //        ////////                if (SMTPUser != null && SMTPPassword != null)
    //        ////////                {
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "mail@visioninfomedia.com";
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "indi";
    //        //                }
    //        eMail.To.Add(toAddress);

    //        //System.Net.Mail.SmtpMail.SmtpServer = server;// Smtpmail;// = new System.Net.Mail.SmtpMail();
    //        //System.Net.Mail.SmtpMail.Send(eMail);
    //        serverSettings ss = getEmailServerCredentials();
    //        if (ss.name.Length > 0)
    //        {
    //            System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(ss.name);
    //            sc.Timeout = 400000;
    //            if (ss.port != 0) sc.Port = ss.port;
    //            if (ss.username.Trim() != "")
    //                sc.Credentials = new NetworkCredential(ss.username, ss.password);
    //            else
    //                sc.Credentials = CredentialCache.DefaultNetworkCredentials;
    //            //sc.Credentials  = CredentialCache.

    //            //                Smtpmail.SmtpServer = "localhost";
    //            //                Smtpmail.Send(eMail);
    //            sc.Send(eMail);
    //            eMail = null;
    //            sc = null;
    //            return "success";
    //        }
    //        else
    //            return "No server settings found.";
    //    }
    //    catch (Exception e)
    //    {
    //        //return false;
    //        return e.Message;
    //    }
    //}

    //public string sendEmail(string toAddress, string fromAddress, string fromAddressDisplayName, bool isHTML, string subject, string content, byte[] attachFile, string attachmentFileName)
    //{
    //    try
    //    {
    //        System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
    //        //eMail = new MailMessage();
    //        if (attachFile != null)
    //        {
    //            //System.Net.Mail.Attachment att;
    //            //att = getAttachment(attachFiles[i]);
    //            //if (att != null)
    //            //    eMail.Attachments.Add(att);
    //            MemoryStream ms = new MemoryStream(attachFile);
    //            eMail.Attachments.Add(new System.Net.Mail.Attachment(ms, attachmentFileName, "image/png"));
    //        }
    //        eMail.IsBodyHtml = isHTML;
    //        //eMail.BodyFormat = System.Net.Mail.MailFormat.Html;
    //        eMail.Body = content;
    //        if (fromAddressDisplayName != "")
    //        {
    //            eMail.From = new System.Net.Mail.MailAddress(fromAddress, fromAddressDisplayName);
    //        }
    //        else
    //        {
    //            eMail.From = new System.Net.Mail.MailAddress(fromAddress);
    //        }
    //        eMail.Subject = subject;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtsperver"] = server;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
    //        ////////                if (SMTPUser != null && SMTPPassword != null)
    //        ////////                {
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "mail@visioninfomedia.com";
    //        //////eMail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "indi";
    //        //                }
    //        eMail.To.Add(toAddress);

    //        //System.Net.Mail.SmtpMail.SmtpServer = server;// Smtpmail;// = new System.Net.Mail.SmtpMail();
    //        //System.Net.Mail.SmtpMail.Send(eMail);
    //        serverSettings ss = getEmailServerCredentials();
    //        if (ss.name.Length > 0)
    //        {
    //            System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(ss.name);
    //            sc.Timeout = 400000;
    //            if (ss.port != 0)
    //                sc.Port = ss.port;
    //            if (ss.username.Trim() != "")
    //                sc.Credentials = new NetworkCredential(ss.username, ss.password);
    //            else
    //                sc.Credentials = CredentialCache.DefaultNetworkCredentials;
    //            //sc.Credentials  = CredentialCache.

    //            //                Smtpmail.SmtpServer = "localhost";
    //            //                Smtpmail.Send(eMail);
    //            sc.Send(eMail);
    //            eMail = null;
    //            sc = null;
    //            return "success";
    //        }
    //        else
    //            return "No server settings found.";
    //    }
    //    catch (Exception e)
    //    {
    //        //return false;
    //        return e.Message;
    //    }
    //}
    #endregion

    #region DataBase Traversal
    // Implemented by 'Imran Gani' on 29-Apr-2013, To reduce database traversal.

    /// <summary>
    /// To get the required value from page dictionary info.
    /// </summary>
    /// <param name="strPagesetRowId">Pageset Id of the page</param>
    /// <param name="sTableName">Table name of the page</param>
    /// <param name="FromField">Name of the field to fetch the value</param>
    /// <param name="WhereCondition">Where condition for the table</param>
    /// <returns>String</returns>
    public static string GetColValueFromPageInfo(string strPagesetRowId, string sTableName, string FromField, string WhereCondition)
    {
        string sReturn = "";
        try
        {
            if (strPagesetRowId == "") return sReturn;
            DataSet dsPageInfo = GetPageDictionaryInfo(strPagesetRowId);
            if (dsPageInfo.Tables.Contains(sTableName))
                if (dsPageInfo.Tables[sTableName].Rows.Count > 0)
                {
                    DataRow[] dr = dsPageInfo.Tables[sTableName].Select(WhereCondition);
                    if (dr.Length > 0)
                        sReturn = dr[0][FromField].ToString();
                }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetColValueFromPageInfo :" + ex.Message);
        }
        finally
        { }
        return sReturn;
    }

    /// <summary>
    /// To get the DataRow from page dictionary info.
    /// </summary>
    /// <param name="strPagesetRowId">Pageset Id of the page</param>
    /// <param name="sTableName">Table name of the page</param>
    /// <param name="WhereCondition">Where condition for the table</param>
    /// <returns>DataRow</returns>
    public static DataRow GetDataRowFromPageInfo(string strPagesetRowId, string sTableName, string WhereCondition)
    {
        DataRow sReturn = null;
        try
        {
            DataSet dsPageInfo = GetPageDictionaryInfo(strPagesetRowId);
            if (dsPageInfo != null && dsPageInfo.Tables.Contains(sTableName))
                if (dsPageInfo.Tables[sTableName].Rows.Count > 0)
                    sReturn = dsPageInfo.Tables[sTableName].Select(WhereCondition)[0];
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDataRowFromPageInfo :" + ex.Message);
        }
        finally
        { }
        return sReturn;
    }

    /// <summary>
    /// To get the DataTable from page dictionary info.
    /// </summary>
    /// <param name="strPagesetRowId">Pageset Id of the page</param>
    /// <param name="sTableName">Table name to fetch from page dictionary</param>
    /// <returns>DataTable</returns>
    public static DataTable GetTableFromPageInfo(string strPagesetRowId, string sTableName)
    {
        DataTable dtTableInfo = null;
        try
        {
            DataSet dsPageInfo = GetPageDictionaryInfo(strPagesetRowId);
            if (dsPageInfo.Tables.Contains(sTableName))
                dtTableInfo = dsPageInfo.Tables[sTableName];
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetTableFromPageInfo :" + ex.Message);
        }
        finally
        { }
        return dtTableInfo;
    }

    /// <summary>
    /// To get the DataSet (Page Distionary) of a page.
    /// </summary>
    /// <param name="strPagesetRowId">Pageset Id of the page</param>
    /// <returns>DataSet</returns>
    public static DataSet GetPageDictionaryInfo(string strPagesetRowId)
    {
        HDDatabase HDD = new HDDatabase();
        DataSet dsPageInfo = null;
        StringBuilder sbQueries = new StringBuilder();
        try
        {
            if (strPagesetRowId == "") return dsPageInfo;

            if (HttpContext.Current.Items.Contains(strPagesetRowId))
                dsPageInfo = (DataSet)HttpContext.Current.Items[strPagesetRowId];
            if (dsPageInfo == null)
            {
                sbQueries.Append("select * from [sy_mnu] where pageset_id = '" + strPagesetRowId + "';");
                sbQueries.Append("select * from [sy_pgs] where af_row_id = '" + strPagesetRowId + "';");
                sbQueries.Append("select pgs_mem.* from [sy_pgs_mem] pgs_mem, [sy_pgs] pgs where pgs_mem.pageset_id = pgs.af_row_id and pgs.af_row_id='" + strPagesetRowId + "';");
                sbQueries.Append("select pg.* from [sy_pg] pg, [sy_pgs] pgs, [sy_pgs_mem] pgs_mem where pg.page_id = pgs_mem.page_id and pgs_mem.pageset_id = pgs.af_row_id and pgs.af_row_id = '" + strPagesetRowId + "' order by pgs_mem.page_seq;");
                sbQueries.Append("select obj.* from [sy_obj] obj, [sy_pgs_mem] pgs_mem, [sy_pgs] pgs where obj.object_id = pgs_mem.object_id and pgs_mem.pageset_id = pgs.af_row_id and pgs.af_row_id = '" + strPagesetRowId + "';");
                sbQueries.Append("select obj_acc.* from [sy_obj_acc] obj_acc, [sy_pgs_mem] pgs_mem, [sy_pgs] pgs where obj_acc.object_id = pgs_mem.object_id and pgs_mem.pageset_id = pgs.af_row_id and pgs.af_row_id = '" + strPagesetRowId + "' and obj_acc.role_id='" + (HttpContext.Current.Session["roleid"] != null ? HttpContext.Current.Session["roleid"].ToString() : "") + "';");
                sbQueries.Append("select * from [sy_usr] where user_id='" + (HttpContext.Current.Session["userid"] != null ? HttpContext.Current.Session["userid"].ToString().Replace("'", "''") : "") + "';");
                //sbQueries.Append("");

                dsPageInfo = HDD.GetDataset(sbQueries.ToString());
                if (dsPageInfo != null)
                {
                    dsPageInfo.Tables[0].TableName = "sy_mnu";
                    dsPageInfo.Tables[1].TableName = "sy_pgs";
                    dsPageInfo.Tables[2].TableName = "sy_pgs_mem";
                    dsPageInfo.Tables[3].TableName = "sy_pg";
                    dsPageInfo.Tables[4].TableName = "sy_obj";
                    dsPageInfo.Tables[5].TableName = "sy_obj_acc";
                    dsPageInfo.Tables[6].TableName = "sy_usr";

                    if (HttpContext.Current.Items.Contains(strPagesetRowId))
                        HttpContext.Current.Items[strPagesetRowId] = dsPageInfo;
                    else
                        HttpContext.Current.Items.Add(strPagesetRowId, dsPageInfo);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetPageDictionaryInfo :" + ex.Message);
        }
        finally
        { 
            HDD = null; 
            sbQueries.Clear(); 
        }
        return dsPageInfo;
    }
    #endregion

    /// <summary>
    /// Use to Remove Special Characters.
    /// </summary>
    /// <param name="sVal">Value to handle special characters.</param>
    /// <returns>Value without special characters.</returns>
    public string RemoveSpecialCharacters(string sVal) // Added by Imran Gani on 24-Jun-2013
    {
        try
        {
            string SplChar = "=\\;.:,+*\'/!-\"#";
            //string SplChar = "\';:[],{}!@#$%^&*()-+<>?/|\\\"";
            for (int i = 0; i < SplChar.Length; i++)
            {
                if (sVal.Contains(SplChar[i].ToString()))
                    sVal = sVal.Replace(SplChar[i].ToString(), "");
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Security: RemoveSpecialCharacters: Error: " + ex.Message);
        }
        finally
        { }
        return sVal;
    }

    public bool ValidateEmailID(string strEmailID)
    {
        try
        {
            if (!string.IsNullOrEmpty(strEmailID))
            {
                string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                      @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                      @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(strRegex);
                if (re.IsMatch(strEmailID))
                    return (true);
                else
                    return (false);
            }
            else
                return (false);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : ValidateEmailID :" + ex.Message);
            return false;
        }
    }
}
